# djangoProject1/views.py
from django.shortcuts import render

from djangoProject1.models import Item, Users


# Create
def create_item(request):
    name = request.POST.get('name')
    description = request.POST.get('description')
    Item.objects.create(name=name, description=description)
    return render(request, 'djangoProject1/items.html')


# Read
def list_items(request):
    items = Item.objects.all()
    return render(request, 'djangoProject1/items.html', {'items': items})


# Update
def update_item(request, pk):
    item = Item.objects.get(pk=pk)
    item.name = request.POST.get('name')
    item.description = request.POST.get('description')
    item.save()
    return render(request, 'djangoProject1/items.html')


# Delete
def delete_item(request, pk):
    item = Item.objects.get(pk=pk)
    item.delete()
    return render(request, 'djangoProject1/items.html')


# 主页面
def home(request):
    return render(request, 'djangoProject1/home.html')  # render是渲染的意思，返回一个页面


# 查看信息
def read(request):
    stu = Users.objects.all()
    context = {'stu': stu}  # 作为一个字典丢到read.html的页面中
    return render(request, 'djangoProject1/read.html', context)


# 添加信息：
def add(request):  # 这里的原理是，在read页面中点击添加信息按钮，
    # 跳转是requesr中get方法，会首先跳到add.html表单中，
    # 在表单输入值reqeust请求方式为post 也就是进行添加操作。
    if request.method == "POST":
        try:
            stu = Users()
            stu.name = request.POST['name']
            stu.age = request.POST['age']
            stu.college = request.POST['college']
            stu.major = request.POST['major']
            stu.grade = request.POST['grade']
            stu.save()
            return render(request, 'djangoProject1/info.html', {"info": "添加成功！"})
        except:
            return render(request, 'djangoProject1/info.html', {"info": "添加失败！"})
    else:
        return render(request, 'djangoProject1/add.html')  # 返回


# 修改信息
def edit(request, sid):
    if request.method == "POST":
        try:
            ob = Users.objects.get(id=sid)
            ob.name = request.POST['name']
            ob.age = request.POST['age']
            ob.college = request.POST['college']
            ob.major = request.POST['major']
            ob.grade = request.POST['grade']
            ob.save()
            return render(request, 'djangoProject1/info.html', {"info": "修改成功！"})
        except:
            return render(request, 'djangoProject1/info.html', {"info": "修改失败！"})
    else:
        stu = Users.objects.get(id=sid)
        context = {'sid': stu}
        return render(request, 'djangoProject1/edit.html', context)


# 删除数据
def dele(request, sid):
    try:
        stu = Users.objects.get(id=sid)
        stu.delete()
        return render(request, 'djangoProject1/info.html', {"info": "删除成功"})
    except:
        return render(request, 'djangoProject1/info.html', {"info": "删除失败"})
